# -*- coding: cp949 -*-
from pydbg import *
from pydbg.defines import *
import time
import win32api, win32con
import win32pdh
import subprocess
import psutil
import os
import thread
import struct
import re

PROCNAME = "Hwp.exe"
gfilename = ""
gdbg = pydbg()
skip = 10719

# Utility libraries included with PyDbg
import utils


# This is our access violation handler
def check_accessv(dbg):
    
    # We skip first-chance exceptions
    if dbg.dbg.u.Exception.dwFirstChance:
            return DBG_EXCEPTION_NOT_HANDLED

    crash_bin = utils.crash_binning.crash_binning()
    crash_bin.record_crash(dbg)
    print crash_bin.crash_synopsis()
    if not os.path.isdir("crash"):
        print "makedir !!"
        os.mkdir("crash")
    print gfilename
    f = open("crash/"+gfilename+".txt", 'w')
    f.write(crash_bin.crash_synopsis())
    f.close()
            
    dbg.terminate_process()
    
    return DBG_EXCEPTION_NOT_HANDLED

def killProcess(msg):
    time.sleep(4)
    print "process kill"
    print "detach %d" % int(msg)
    time.sleep(1)
    gdbg.detach()
    for proc in psutil.process_iter():
        if proc.name == PROCNAME:
            proc.kill()



def search(dirname):
    flist = os.listdir(dirname)
    for f in flist:
        next = os.path.join(dirname, f)
        if os.path.isdir(next):
            search(next)
        else:
            doFileWork(next)

def doFileWork(filename):
    ext = os.path.splitext(filename)[-1]
    if ext == '.hwp':
        print filename
        num = re.findall('[0-9]',filename)
        strFilename = ''
        for i in num:
            strFilename+=i
        print strFilename
        if skip > int(strFilename):
            print "skip %d",int(strFilename)
            return

        global gfilename
        gfilename = filename[2:]
        subprocess.Popen(filename[2:], shell=True)
        time.sleep(1)
        out = 0
        pid = 0
        while 1:
            if out == 1:
                break
            for proc in psutil.process_iter():
                pid = proc.pid
                if proc.name == PROCNAME:
                    print pid
                    out = 1
                    break

        print "Attach %d" % pid
        thread.start_new_thread(killProcess,(pid,))

        try:
            dbg = pydbg()
            gdbg = dbg
            dbg.attach(pid)
            dbg.set_callback(EXCEPTION_ACCESS_VIOLATION,check_accessv)
            dbg.run()

            for proc in psutil.process_iter():
                if proc.name == PROCNAME:
                    proc.kill()

        except:
            for proc in psutil.process_iter():
                if proc.name == PROCNAME:
                    proc.kill()


search('./')





